﻿using System.IO;

namespace Behaviorize.TextFormatting
{
	public static class TextFormatter
	{
		public static string ToText(string pascal, bool appendLeadingSpace, params object[] args)
		{
			string text;

			using (StringWriter writer = new StringWriter())
			using (StringReader reader = new StringReader(pascal))
			{
				int c = reader.Read();
				int argIndex = 0;

				while (c != -1)
				{
					char character = (char)c;

					if (character == '_' && args.Length > argIndex)
					{
						writer.Write(" " + args[argIndex++]);
					}
					else if (char.IsUpper(character) || char.IsDigit(character))
					{
						writer.Write(" " + char.ToLowerInvariant(character));
					}
					else
					{
						writer.Write(character);
					}

					c = reader.Read();
				}

				text = writer.ToString().Trim();
			}

			if (appendLeadingSpace) text = text.Insert(0, " ");
			return text;
		}
	}
}